'use strict';

const { Controller } = require('egg');
const { Op } = require('sequelize');
const dayjs = require('dayjs');
class RouterController extends Controller {
  async rank() {
    let list = []
    const { query } = this.ctx;
    // 月、年、所有
    let dateType = query.dateType || 'month';
    // 鱼获或者龟王
    let dataType = query.dataType || 'fish';
    let where = {}
    if (dateType === 'month') {
        where = {
            publish_time: {
            [Op.gte]: dayjs().startOf('month').format('YYYY-MM-DD'),
            [Op.lte]: dayjs().endOf('month').format('YYYY-MM-DD')
            }
        }
    } else if (dateType === 'year') {
        where = {
            publish_time: {
            [Op.gte]: dayjs().startOf('year').format('YYYY-MM-DD'),
            [Op.lte]: dayjs().endOf('year').format('YYYY-MM-DD')
            }
        }
    }
    if (dataType === 'fish') {
       let fishData = await this.ctx.model.Fish.findAll()
       let data = await this.ctx.model.Member.findAll({
            include: [
                {
                    model: this.ctx.model.FishCatch,
                    where: {
                        ...where
                    },
                }
            ]
        })
        // 每个人的鱼获，需要按照每个人的总鱼获进行排序
        list = data.map(item => {
            let sum = 0
            let fishMap = {

            }
            item = item.dataValues
            item.fishCatches.forEach(fish => {
                fish = fish.dataValues
                sum += fish.count
                let findFish = fishData.find(f => f.id === fish.fish_id)
                if (findFish) {
                    if (fishMap[findFish.name]) {
                        fishMap[findFish.name] += fish.count
                    } else {
                        fishMap[findFish.name] = fish.count
                    }
                }
            })
            let fishList = []
            for (let key in fishMap) {
                fishList.push({
                    name: key,
                    count: fishMap[key]
                })
            }
            return {
                member: {
                    ...item,
                    fishCatches: undefined
                },
                sum,
                fishList
            }
        })
    }

    if (dataType === 'turtle') {

    }
    this.ctx.success(list);
  }

  // 月度、年度统计
  async total() {
      let list = []
      const { query } = this.ctx;
      // 月、年、所有
      let dateType = query.dateType || 'month';
      let formatMap = {
          'month': 'YYYY-MM',
          'year': 'YYYY'
      }
      let where = {
          member_id: query.member_id
      }
      // 鱼的种类
        let fishCategoryList = await this.ctx.model.Fish.findAll()
      fishCategoryList = fishCategoryList.map(item => item.dataValues)
      // 鱼获数据
        let fishData = await this.ctx.model.FishCatch.findAll({
            where: {
                ...where,
            },
        })
      fishData = fishData.map(item => item.dataValues)
       // 打龟数据
         let turtleData = await this.ctx.model.Turtle.findAll({
            where: {
                ...where,
            }
         })
      turtleData = turtleData.map(item => item.dataValues)
       // 花费数据
            let costData = await this.ctx.model.Cost.findAll({
                where: {
                    ...where,
                }
            })
      costData = costData.map(item => item.dataValues)
      // 判断这些数据一共涉及多少个月
        let monthList = []
        let fishMonthMap = {
        }
        fishData.forEach(item => {
            let month = dayjs(item.publish_time).format(formatMap[dateType])
            if (fishMonthMap[month]) {
                fishMonthMap[month].push(item)
            } else {
                fishMonthMap[month] = [item]
            }
            if (!monthList.includes(month)) {
                monthList.push(month)
            }
        })
        let turtleMonthMap = {}
        turtleData.forEach(item => {
            let month = dayjs(item.publish_time).format(formatMap[dateType])
            if (turtleMonthMap[month]) {
                turtleMonthMap[month].push(item)
            } else {
                turtleMonthMap[month] = [item]
            }
            if (!monthList.includes(month)) {
                monthList.push(month)
            }
        })
        let costMonthMap = {}
        costData.forEach(item => {
            let month = dayjs(item.create_time).format(formatMap[dateType])
            if (costMonthMap[month]) {
                costMonthMap[month].push(item)
            } else {
                costMonthMap[month] = [item]
            }
            if (!monthList.includes(month)) {
                monthList.push(month)
            }
        })

      /**
       *  days: 0,
       *                     fishDays: 0,
       *                     // 放流次数
       *                     releaseCount: 0,
       *                     // 鱼获次数
       *                     fishCount: 0,
       *                     // 鱼获列表，按鱼种分类
       *                     fishList: [],
       *                     // 龟王次数
       *                     turtleCount: 0,
       *                     // 花费总额
       *                     cost: 0,
       *                     // 打龟率
       *                     turtleRate: 0,
       *                     // 去年同期鱼获
       *                     lastYearFish: 0,
       *                     // 最大中鱼天数间隔
       *                     maxFishDays: 0,
       *                     // 间隔最大中鱼的开始、结束时间
       *                     maxFishDaysStart: '',
       *                     maxFishDaysEnd: '',
       *                     // 最大连龟天数
       *                     maxTurtleDays: 0,
       * @type {{}}
       */
      let result = []


      // 计算每个月的数据
      for (const key of monthList) {
          const fishList = fishMonthMap[key] || []
          const turtleList = turtleMonthMap[key]  || []
          const costList = costMonthMap[key] || []
          // 出勤天数 包括打鱼和打龟,按天去重
          let days = 0
          let fishDays = 0
          let turtleDays = turtleList.length
          let cost = 0
          let releaseCount = fishList.filter(item => item.release_type === '放流').length
          let fishCount = fishList.filter(item => item.count).length
          // 按天要去重
          let categoryMap = {}
          let dayMap = {}
          fishList.forEach(item => {
              let day = dayjs(item.publish_time).format('YYYY-MM-DD')
              if (!dayMap[day]) {
                  dayMap[day] = true
                  days++
                  fishDays++
              }
              // 根据鱼的种类计算数量
              if (categoryMap[item.fish_id]) {
                  categoryMap[item.fish_id] += item.count
              } else {
                  categoryMap[item.fish_id] = item.count
              }
          })
          dayMap = {}
          turtleList.forEach(item => {
              let day = dayjs(item.publish_time).format('YYYY-MM-DD')
              if (!dayMap[day]) {
                  dayMap[day] = true
                  days++
              }
          })
          costList.forEach(item => {
              cost += Number(item.amount)
          })

          // 鱼获概览
          let fishListResult = []
          for (let key in categoryMap) {
              let findFish = fishCategoryList.find(f => f.id == key)
              if (findFish) {
                  fishListResult.push(`${findFish.name}x${categoryMap[key]}条`)
              }
          }
          result.push({
              month: key,
              attendance: days,
              catch: fishDays, // 中鱼天数
              turtle: turtleDays, // 打龟天数
              cost, //花费
              release: releaseCount, // 放流次数
              fish: fishCount, // 鱼获次数
              turtle_rate: turtleDays / days ? (turtleDays / days) * 100 + '%' : '', // 打龟率
              fish_overview: fishListResult.join(','), // 鱼获列表
              last_year: 0, // 去年同期鱼获
          })
      }

      // 根据结果去计算每个月同比去年的数据
      for (let i = 0; i < result.length; i++) {
          let item = result[i]
          let lastYear = dayjs(item.month).subtract(1, 'year').format(formatMap[dateType])
          let lastYearItem = result.find(r => r.month === lastYear)
          if (lastYearItem) {
              item.last_year = lastYearItem.fish
          }
      }
      this.ctx.success(result);
  }
}

module.exports = RouterController;
